'''
Created on Aug 28, 2013

@author: loski07@gmail.com
'''

from controller.deviceManager import DeviceManager
from controller.visitor import AlphaSorter, ID3Sorter
from model.models import *
import os



class SongManager(object):
    """
    Class with operations to manage the logical song structure.
    """
    

    def get_folder(self, current_dir):
        """
        Method that creates a Tree structure of the songs and folders under the path specified
        
        @param current_dir: base folder to scan.
        @return: returns the Tree structure under the root.
        """
        tree = Tree(current_dir)
        for x in os.listdir(current_dir):
            if not x.startswith('.'):
                subitem = os.path.join(current_dir, x)
                if os.path.isdir(subitem):
                    tree.add_subdir(self.get_folder(subitem))
                elif subitem[-4:].lower() in ['.mp3', '.wma']:
                    tree.add_song(Song(x, os.path.realpath(subitem)))
        return tree
    
    def sort_tree_alpha(self, song_tree):
        """
        Sorts the song tree in alphabetic order
        
        @param song_tree: Tree to order
        @return: Tree ordered in alphabetical order
        """
        alpha_sorter = AlphaSorter()
        return alpha_sorter.visit(song_tree)
        
    def sort_tree_id3(self, song_tree):
        """
        Sorts the song tree using the order field of the id3 tags
        
        @param song_tree: Tree to order
        @return: Tree ordered using id3 tags
        """
        id3_sorter = ID3Sorter()
        return id3_sorter.visit(song_tree)
    
    
    def check_src_folders(self, folder_list):
        """
        Checks the existence of the folders in the list as well as verifies that they are not
        subfolders one of each other.
        
        @param folder_list: list of folder names.
        @return: list of folder names of the wrong folders and list of dictionaries
            with keys 'name' and 'size' that stores the full path to the target and
            the available size in KB.
        """
        dsm = DeviceManager()
        wrong_folders = []
        ok_folders = []
        for fldr in folder_list:
            if not os.path.exists(fldr):
                wrong_folders.append(fldr)
                
            for chk_fldr in ok_folders:
                r_fldr = os.path.realpath(fldr)
                r_chk_fldr = os.path.realpath(chk_fldr)
                if r_fldr in r_chk_fldr:
                    wrong_folders.append(fldr)
                if r_chk_fldr in r_fldr:
                    wrong_folders.append(chk_fldr)
                    ok_folders.remove(r_chk_fldr)
                    ok_folders.append(r_fldr)
        
        res_src_folder = []
        for aux in ok_folders:
            res_src_folder.append({'name': aux, 'size': dsm.calculate_folder_size(aux)})
        return res_src_folder, wrong_folders
